<template>
  <div class="chat" v-if="!isLoading">
    <div class="chat-box">
      <div class="chat-box__header">
        <el-row
          ><el-col :span="4"
            ><div class="chat-name" @click="reload">
              <Svg-icon icon-class="logo" />
              TYChat
            </div> </el-col
          ><chat-header></chat-header
        ></el-row>
      </div>
      <el-row>
        <router-view />
      </el-row>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, nextTick } from "vue";
import chatHeader from "../components/header/index.vue";
import LoadingBar from "../plugins/loadingBar";
import { useUserPinia } from "../pinia/user";
import { useFriendPinia } from "../pinia/friend";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
import Cookie from "../plugins/cookie";
import { ElMessage } from "element-plus";
import { useSocketPinia } from "@/pinia/socket";
import { Base64 } from "js-base64";

const userStore = useUserPinia();
const friendStore = useFriendPinia();
const router = useRouter();
const route = useRoute();
const socketStore = useSocketPinia();

/**
 * 该组件的根元素的高度
 */
let winHei = ref<string>("");

/**
 * 浏览器的可视高度改变则组件的根元素的高度也随之改变
 */
const handleToWid: () => void = (): void => {
  // 获取浏览器的可视高度
  const hei: number =
    globalThis.innerHeight ||
    document.body.clientHeight ||
    document.documentElement.clientHeight;
  if (hei <= 555) {
    winHei.value = "555px";
    return;
  }
  winHei.value = `${hei}px`;
};

const isLoading = ref<boolean>(true);
// 初始化组件根元素的高度
onBeforeMount(() => {
  const loadingBar = new LoadingBar();
  loadingBar.start();
  userStore
    .getUserInfo()
    .then((code: number) => {
      if (code === 1) {
        if (userStore.isFirst) {
          loadingBar.finsh();
          router.replace({ name: "setUserInfo" });
        } else if (route.path.includes("contact")) {
          friendStore
            .getAllFriends({ slefId: Base64.encode(userStore.user.userId) })
            .then((data) => {
              if (data.code === 1) {
                loadingBar.finsh();
                isLoading.value = false;
                nextTick(() => {
                  handleToWid(); // 给浏览器添加监听窗口大小变化的事件
                  window.addEventListener("resize", handleToWid);
                });
                // 开始连接websocket
                socketStore.SOCKET_CREATE();
                new Image().src = userStore.user.bkImg;
              } else if (data.code === -1) {
                Cookie.deleteCookie("token");
                loadingBar.unMount();
                ElMessage.error("token已失效，请重新登录");
                router.replace({ name: "login" });
              } else {
                loadingBar.unMount();
                router.push("/404");
              }
            })
            .catch(() => {
              loadingBar.unMount();
              router.push("/404");
            });
        } else {
          loadingBar.finsh();
          isLoading.value = false;
          nextTick(() => {
            handleToWid(); // 给浏览器添加监听窗口大小变化的事件
            window.addEventListener("resize", handleToWid);
          });
          // 开始连接websocket
          socketStore.SOCKET_CREATE();
        }
      }
      // 代表token已经过期
      else if (code === -1) {
        Cookie.deleteCookie("token");
        loadingBar.unMount();
        ElMessage.error("token已失效，请重新登录");
        router.replace({ name: "login" });
      } else {
        loadingBar.unMount();
        router.push("/404");
      }
    })
    .catch(() => {
      loadingBar.unMount();
      router.push("/404");
    });
});
// 组件卸载前移除该事件
onBeforeRouteLeave(() => {
  window.removeEventListener("resize", handleToWid);
  socketStore.SOCKET_CLOSE({ callback: () => console.log("socket连接已断开") });
});

// 重新加载页面
const reload = () => location.replace("/");
</script>

<style lang="scss" scoped>
.spin {
  position: absolute;
  top: 13px;
  right: 20px;
  @include setWidHei(24px, 24px);
  animation: loading-rotate 1s linear infinite;
}
@keyframes loading-rotate {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}
.chat {
  height: v-bind(winHei);
  position: relative;
  min-width: 880px;

  &-name {
    height: 55px;
    line-height: 55px;
    text-align: center;
    color: #fff;
    cursor: pointer;
    font: {
      size: 1.5rem;
      weight: 700;
      family: FZShuTi, STHupo, STCaiyun;
    }
  }

  &-box {
    box: {
      shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
      sizing: border-box;
    }
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);

    &__header {
      height: 55px;
      background-color: #a0cfff;
      box-sizing: border-box;
      /* 防止用户请求与某一好友消息记录时该组件抖动 */
      margin-top: 1px;
      padding-bottom: -1px;
    }
  }
}
</style>
